package com.srv.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.srv.control.HashControl;
import com.srv.dao.DAOReserva;
import com.srv.pojo.Reserva;
import com.srv.pojo.Usuario;

/**
 * Servlet implementation class EfetuarReservaServlet
 */
@WebServlet("/AlterarReservaServlet")
public class AlterarReservaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AlterarReservaServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String strRescode = request.getParameter("rescode");
		String strTipoOperacao = request.getParameter("tipo_operacao");
		
		int rescode = Integer.parseInt(strRescode.trim());
		
		HttpSession session = request.getSession(false);
		
		try {
			
			if (session.getAttribute("email") != null) {
				String rs = session.getAttribute("email").toString() + "S.R.V";
				rs = HashControl.md5(rs);

				if (!session.getAttribute("controle").toString().equals(rs)) {
					request.setAttribute("msg", "É necessário fazer o login para alterar uma reserva!");
					RequestDispatcher view = request.getRequestDispatcher("index.jsp");
					view.forward(request, response);
				} else {
					DAOReserva daoReserva = new DAOReserva();
					Reserva reserva = daoReserva.getReservaByRescode(rescode);
					session.setAttribute("reserva", reserva);
					
					if("excluir".equals(strTipoOperacao)){
						daoReserva.delete(reserva);
					}
					if("alterar".equals(strTipoOperacao)){
						daoReserva.update(reserva);
					}
					
					Usuario user = new Usuario();
					user.setEmail((String)session.getAttribute("email"));
					List<Reserva> listaReserva = daoReserva.getReservaList(user);
					session.setAttribute("reservas", listaReserva);
					
					request.getRequestDispatcher("LoginServlet").forward(request, response);
				}
			} else {
				RequestDispatcher view = request.getRequestDispatcher("index.jsp");
				view.forward(request, response);
			}
		} catch (Exception e) {
			session.invalidate();
			request.setAttribute("msg",
					"Ocorreu um erro." + e.getMessage());
			RequestDispatcher view = request.getRequestDispatcher("index.jsp");
			view.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
